#!/bin/bash
# OpenMPTCProuter VPS端一键安装脚本（优化版）
# 版本：v8.3 | 更新日期：2025-03-23
echo "版本：v1.5"
# 配置参数
SUPPORTED_KERNELS=("5.4" "6.1" "6.6")
OFFICIAL_SCRIPT="https://www.openmptcprouter.com/server/debian-x86_64.sh"
DOWNLOAD_PROXY=""
DEFAULT_KERNEL="6.1"
CF_WORKER_MIRROR="omr.8080k.eu.org"  # 替换为您的 Workers 地址

# 颜色定义
RED='\033[31m'; GREEN='\033[32m'; YELLOW='\033[33m'; RESET='\033[0m'

# 国内镜像源列表（用于 bullseye）
MIRRORS=(
  "https://mirrors.163.com/debian"
  "https://mirrors.ustc.edu.cn/debian"
  "https://repo.huaweicloud.com/debian"
  "https://mirrors.tencent.com/debian"
  "https://mirrors.aliyun.com/debian"
)

# 国内存档源列表（用于 buster-backports）
ARCHIVE_MIRRORS=(
  "https://mirrors.163.com/debian-archive/debian"
  "https://mirrors.aliyun.com/debian-archive/debian"
  "https://repo.huaweicloud.com/debian-archive/debian"
)

# 自动安装依赖
check_and_install_deps() {
  echo -e "${YELLOW}检查并安装必要的依赖...${RESET}"
  local packages=("curl" "wget" "gnupg2" "ufw" "jq" "lsb-release")
  for pkg in "${packages[@]}"; do
    if ! dpkg -l | grep -q "$pkg"; then
      echo -e "${YELLOW}安装 $pkg...${RESET}"
      apt install -y "$pkg"
    fi
  done
}

# 选择APT源
choose_mirror() {
  if [[ "$(lsb_release -cs)" == "bookworm" ]]; then
    while true; do
      echo -e "${YELLOW}是否更换APT源？${RESET}"
      echo "1) 163 源"
      echo "2) 清华源"
      echo "3) 阿里云源"
      echo "0) 不更换（默认）"
      read -p "请输入选项 (0/1/2/3): " choice < /dev/tty
      case "$choice" in
        1) SOURCE_URL="https://mirrors.163.com/debian/"; break ;;
        2) SOURCE_URL="https://mirrors.tuna.tsinghua.edu.cn/debian/"; break ;;
        3) SOURCE_URL="https://mirrors.aliyun.com/debian/"; break ;;
        0) echo -e "${BLUE}跳过更换APT源。${RESET}"; return ;;
        *) echo -e "${RED}无效输入，请重新选择！${RESET}" ;;
      esac
    done
    echo -e "${YELLOW}正在更换APT源...${RESET}"
    cat << EOF > /etc/apt/sources.list
deb $SOURCE_URL bookworm main contrib non-free
deb-src $SOURCE_URL bookworm main contrib non-free
deb $SOURCE_URL bookworm-updates main contrib non-free
deb-src $SOURCE_URL bookworm-updates main contrib non-free
deb $SOURCE_URL bookworm-security main contrib non-free
deb-src $SOURCE_URL bookworm-security main contrib non-free
EOF
    apt update
  fi
}

# 选择内核
choose_kernel() {
  while true; do
    echo -e "${YELLOW}请选择要安装的内核版本:${RESET}"
    echo "1) 5.4"
    echo "2) 6.1（默认）"
    echo "3) 6.6"
    read -p "请输入选项 (1/2/3): " choice < /dev/tty
    case "$choice" in
      1) KERNEL="5.4"; break ;;
      2) KERNEL="6.1"; break ;;
      3) KERNEL="6.6"; break ;;
      *) echo -e "${RED}无效选择，请重新输入！${RESET}" ;;
    esac
  done
}

# 选择下载方式
choose_download_method() {
  while true; do
    echo -e "${YELLOW}请选择安装程序下载方式:${RESET}"
    echo "1) 直接下载（不使用加速，默认）"
    echo "2) 使用默认加速（ghproxy.com）"
    echo "3) 输入自定义加速链接"
    read -p "请输入选项 (1/2/3): " choice < /dev/tty
    case "$choice" in
      1) DOWNLOAD_PROXY=""; break ;;
      2) DOWNLOAD_PROXY="https://ghproxy.com/"; break ;;
      3) 
        read -p "请输入自定义加速链接: " custom_proxy < /dev/tty
        DOWNLOAD_PROXY="$custom_proxy"
        break ;;
      *) echo -e "${RED}无效选择，请重新输入！${RESET}" ;;
    esac
  done
}

# 更新 GitHub Hosts
update_github_ip() {
  echo -e "${YELLOW}正在更新 GitHub 的 IP 地址...${RESET}"
  GITHUB_IPS=$(curl -s https://api.github.com/meta | jq -r '.git[]')
  if [[ -z "$GITHUB_IPS" ]]; then
    echo -e "${RED}无法获取 GitHub 最新 IP，跳过更新 /etc/hosts${RESET}"
    return
  fi
  for ip in $GITHUB_IPS; do
    sed -i "/github.com/d" /etc/hosts
    echo "$ip github.com" >> /etc/hosts
    echo "$ip objects.githubusercontent.com" >> /etc/hosts
    echo "$ip raw.githubusercontent.com" >> /etc/hosts
  done
  echo -e "${GREEN}GitHub 的 IP 地址已更新！${RESET}"
}

# 测试源是否可用
test_source() {
  local url=$1
  local dist=$2
  echo -e "${YELLOW}测试 $url $dist 是否可用...${RESET}"
  if curl -s -I "$url/dists/$dist/Release" | grep -q "200 OK"; then
    echo -e "${GREEN}$url $dist 可用${RESET}"
    return 0
  else
    echo -e "${RED}$url $dist 不可用${RESET}"
    return 1
  fi
}

# 下载并优化官方安装脚本
download_script() {
  echo -e "${YELLOW}获取安装程序...${RESET}"
  local retries=3
  for ((i=1; i<=retries; i++)); do
    if curl -kL "${DOWNLOAD_PROXY}${OFFICIAL_SCRIPT}" -o /tmp/omr_install.sh; then
      rm -f /etc/apt/sources.list.d/bullseye.list
      rm -f /etc/apt/sources.list.d/buster-backports.list
      
      local bullseye_source="deb http://deb.debian.org/debian bullseye main"
      local buster_backports_source="deb http://archive.debian.org/debian buster-backports main"
      
      # 测试并替换 bullseye 源
      for mirror in "${MIRRORS[@]}"; do
        if test_source "$mirror" "bullseye"; then
          sed -i "s|$bullseye_source|deb $mirror bullseye main|g" /tmp/omr_install.sh
          bullseye_source="deb $mirror bullseye main"
          echo -e "${GREEN}使用 $mirror 替换 bullseye 源${RESET}"
          break
        fi
      done
      if [ "$bullseye_source" == "deb http://deb.debian.org/debian bullseye main" ]; then
        echo -e "${YELLOW}所有国内源 bullseye 不可用，保留 deb.debian.org${RESET}"
      fi
      
      # 测试并替换 buster-backports 源（优先使用国内存档源）
      local found_available=false
      for archive_mirror in "${ARCHIVE_MIRRORS[@]}"; do
        if test_source "$archive_mirror" "buster-backports"; then
          sed -i "s|$buster_backports_source|deb $archive_mirror buster-backports main|g" /tmp/omr_install.sh
          buster_backports_source="deb $archive_mirror buster-backports main"
          echo -e "${GREEN}使用 $archive_mirror 替换 buster-backports 源${RESET}"
          found_available=true
          break
        fi
      done
      
      # 如果所有国内存档源不可用，回退到 archive.debian.org
      if ! $found_available; then
        echo -e "${YELLOW}所有国内存档源 buster-backports 不可用，使用 archive.debian.org${RESET}"
        if test_source "http://archive.debian.org/debian" "buster-backports"; then
          echo -e "${GREEN}archive.debian.org buster-backports 可用${RESET}"
        else
          echo -e "${RED}archive.debian.org buster-backports 不可用，请检查网络${RESET}"
        fi
      fi
      
      # 替换官方脚本中的 repo.openmptcprouter.com 为 CF Workers 反代地址
      sed -i "s|repo.openmptcprouter.com|$CF_WORKER_MIRROR|g" /tmp/omr_install.sh
      echo -e "${GREEN}已将 repo.openmptcprouter.com 替换为 $CF_WORKER_MIRROR${RESET}"
      
      return 0
    fi
    sleep $((i*2))
  done
  echo -e "${RED}安装脚本下载失败${RESET}" && exit 1
}

# 开放端口
open_required_ports() {
  echo -e "${YELLOW}是否开放 OpenMPTCPRouter 需要的所有端口？ (y/n)${RESET}"
  read -r answer < /dev/tty
  if [[ "$answer" == "y" ]]; then
    echo -e "${YELLOW}正在开放必要端口...${RESET}"
    REQUIRED_PORTS=(65222 65101 65280 65001 65500 65301 65201:65208 65400 65401 65228:65231 65248:65252 443 65311:65312)
    for port in "${REQUIRED_PORTS[@]}"; do
      ufw allow "$port"
    done
    ufw allow icmp  
    echo -e "${GREEN}所有必要端口已开放！${RESET}"
  else
    echo -e "${YELLOW}已跳过端口开放步骤。${RESET}"
  fi
}

# 主执行流程
main() {
  [[ $EUID -eq 0 ]] || { echo -e "${RED}需要 root 权限${RESET}"; exit 1; }
  [[ -e /dev/net/tun ]] || { echo -e "${RED}TUN 设备未启用${RESET}"; exit 1; }
  check_and_install_deps
  choose_mirror
  choose_kernel
  choose_download_method
  update_github_ip
  download_script
  echo -e "${YELLOW}安装 OpenMPTCPRouter (内核:$KERNEL)...${RESET}"
  chmod +x /tmp/omr_install.sh
  export DEBIAN_FRONTEND=noninteractive KERNEL
  /tmp/omr_install.sh || { echo -e "${RED}主安装流程失败${RESET}"; exit 1; }
#  echo -e "${GREEN}[成功] 服务已启动！管理地址: http://$(curl -s icanhazip.com):8080${RESET}"
  open_required_ports
}

# 入口点
if [ -t 0 ]; then
  echo -e "${RED}请通过管道执行：curl -sSL URL | bash${RESET}"
  exit 1
else
  main "$@"
fi